//
//  NewInstallViewController.m
//  CarLife
//
//  Created by yu on 2018/2/9.
//  Copyright © 2018年 jpas. All rights reserved.
//

#import "NewInstallViewController.h"
#import "NewInstallCell.h"
#import "EquipModel.h"
#import "TakePhotoViewController.h"
#import "ScanQRCodeViewController.h"
#import "PhotoViewController.h"

@interface NewInstallViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *equipModels;
//拍完照片的设备号数组
@property (nonatomic, strong) NSMutableArray *eqnosArray;
@property (nonatomic, strong) NSMutableArray *eqnosHasSuffixArray;

@property (nonatomic, assign) NSInteger index;

@end

@implementation NewInstallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = [self workorderType];
    [self setLeftImageNamed:@"back_white" action:@selector(returnAction)];
    [self.tableView registerNib:NIB_NAMED(@"NewInstallCell") forCellReuseIdentifier:@"NewInstallCellIdentifier"];
//    PPLog(@"派工备注 == %@",self.woModel.installComments);
    
    if (self.enterInstallType == EnterByNewInstallNormal) {
        self.equipModels = [NSMutableArray array];
        [self loadEqList];// 加载设备清单
        [self loadInstalledEq];//加载已安装完的设备
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEqNoAction:) name:@"kSendEqNoNotification" object:nil];
}

- (void)loadInstalledEq
{
    PPLog(@"workEqnos = %@",self.woModel.workEqnos);
    //868120777761640,868120777761641,868120777761642
    NSString *workEqnos = self.woModel.workEqnos;
    if (workEqnos.length >= 15) {
//        if ([workEqnos containsString:@","]) {
            NSArray *equips = [workEqnos componentsSeparatedByString:@","];
            [equips enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                PPLog(@"single eqno = %@",obj);
                NSString *eqno = [obj substringToIndex:15];
//                PPLog(@"eqno = %@",eqno);
                
                NSString *index = [obj substringFromIndex:15];
//                PPLog(@"index = %@",index);
                
                EquipModel *eqModel = self.equipModels[index.integerValue];
                eqModel.eqNoSuffix = obj;
                eqModel.isFinish = YES;
                eqModel.eqNo = eqno;
                [self.tableView reloadData];
            }];
//        }
    }
}

#pragma - notification -

- (void)receiveEqNoAction:(NSNotification *)noti {
    PPLog(@"NSNotification = %@",noti.object);
    NSString *eqNo = noti.object;
    if (eqNo.length)
    {
        EquipModel *eqModel = self.equipModels[_index];
        NSString *eqNoSuffix = NSStringFormat(@"%@%ld",eqNo,_index);
        eqModel.eqNo = eqNo;
        eqModel.eqNoSuffix = eqNoSuffix;
        eqModel.isFinish = YES;
        [self.tableView reloadData];
        
        // 更新工单设备号
        [self uploadEqnos];
    }
}

- (void)uploadEqnos
{
    NSMutableArray *eqnos = [[self.equipModels valueForKey:@"eqNoSuffix"] mutableCopy];
    PPLog(@"AllPhotoCount = %ld",eqnos.count);
    [eqnos removeObjectsAtIndexes:[eqnos indexesOfObjectsPassingTest:^BOOL(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return ![obj isKindOfClass:[NSString class]] || !obj.length;
    }]];
    NSString *jointEqnos = [eqnos componentsJoinedByString:@","];
    PPLog(@"jointEqnos = %@",jointEqnos);
    
    [self.requestTool workorderUpdateStatus:self.woModel.woId status:@"9" workEqnos:jointEqnos success:^(BOOL isFinish) {
        //更新设备号
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kReloadWorkOrderListNotification" object:nil];
    } failure:^(NSString *error) {
        PPLog(@"workorder update status error = %@",error);
    }];
}

- (void)loadEqList {
    // GT20Cx2，GT750x1,GT590x3
    NSString *eq = self.woModel.installComments;
    PPLog(@"install comments = %@",eq);
    if ([eq containsString:@"，"])
    {
        eq = [eq stringByReplacingOccurrencesOfString:@"，" withString:@","];
    }
    
    NSArray *equips = [eq componentsSeparatedByString:@","];
    [equips enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *x = obj;
        if ([x containsString:@"X"])
        {
            x = [x stringByReplacingOccurrencesOfString:@"X" withString:@"x"];
        }
        NSArray *equips = [x componentsSeparatedByString:@"x"];
        NSInteger nums  = [equips.lastObject integerValue];
        for (NSInteger i = 0; i < nums; i++) {
            EquipModel *eqModel = [[EquipModel alloc] init];
            eqModel.eqType = ((NSString *)equips.firstObject).uppercaseString;
            eqModel.eqNo = @"x1";
            eqModel.isFinish = NO;
            [self.equipModels addObject:eqModel];
//            PPLog(@"eqModel = %@",equips.firstObject);
        }
        [self.tableView reloadData];
    }];
}

#pragma mark - return back -
- (void)returnAction
{
    if (self.eqnosArray.count) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前工单还未提交，此时退出所有信息将失效,是否确定退出？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alert addAction:cancelAction];
        [alert addAction:certainAction];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.enterInstallType == EnterByNewInstallDetail) {
        return 1;
    } else {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return !section?1:self.equipModels.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewInstallCell *cell = [NewInstallCell initTableViewCellWith:tableView indexPath:indexPath];
    if (!indexPath.section) {
        cell.woModel = self.woModel;
    } else {
        EquipModel *eqModel = self.equipModels[indexPath.row];
        cell.eqModel = eqModel;
        cell.photoBtn.tag = indexPath.row+1;
    }
    
#pragma mark - taking photo action -
    @weakify(self);
    [cell setPhotoActionBlock:^(NSInteger index) {
        @strongify(self);
        _index = index;
        EquipModel *eqModel = self.equipModels[indexPath.row];
        PhotoViewController *p = [[PhotoViewController alloc] init];
        p.takePhotoType = @"1";
        p.eqType = eqModel.eqType;
//        PPLog(@"设备型号：%@",eqModel.eqType);
        [self.navigationController pushViewController:p animated:YES];
    }];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section) {
        if (self.equipModels.count) {
            UIView *bgView = [[UIView alloc] init];
            bgView.backgroundColor = [UIColor clearColor];
            
            UIButton *submitBtn = [[UIButton alloc] init];
            [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
            [submitBtn setBackgroundColor:kBaseColor];
            [submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
            [bgView addSubview:submitBtn];
            
            submitBtn.sd_layout
            .leftSpaceToView(bgView, 15)
            .topSpaceToView(bgView, 15)
            .rightSpaceToView(bgView, 15)
            .heightIs(45);
            submitBtn.sd_cornerRadius = @(3);
            return bgView;
        }
    }
    return nil;
}

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

#pragma mark - submit action
- (void)submitAction {
    
    for (EquipModel *eqModel in self.equipModels) {
        PPLog(@"%@",eqModel.eqNo);
        if (eqModel.eqNo.length != 15) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"当前工单未完成，请稍候再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
    }
    
    NSMutableArray *eqnos = [[self.equipModels valueForKey:@"eqNoSuffix"] mutableCopy];
//    PPLog(@"AllPhotoCount = %ld",eqnos.count);
    [eqnos removeObjectsAtIndexes:[eqnos indexesOfObjectsPassingTest:^BOOL(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return ![obj isKindOfClass:[NSString class]] || !obj.length;
    }]];
    NSString *jointEqnos = [eqnos componentsJoinedByString:@","];
    PPLog(@"jointEqnos = %@",jointEqnos);
    
    [self.requestTool workorderUpdateStatus:self.woModel.woId status:@"3" workEqnos:jointEqnos success:^(BOOL isFinish) {
        [MBProgressHUD showToast:@"提交成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kReloadWorkOrderListNotification" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSString *error) {
        PPLog(@"workorder update status error = %@",error);
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section ? 90:0.001;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!section) {
        return @"工单信息";
    } else {
        if (self.equipModels.count) {
            return @"设备清单";
        } else {
            return @"注：该工单无设备清单，请联系管理员。";
        }
    }
}

- (NSString *)workorderType {
    NSString *wordOrderType = NSStringFormat(@"%@",self.woModel.wordOrderType);
    if ([wordOrderType isEqualToString:@"0"]) {
        wordOrderType = @"新装";
    } else if ([wordOrderType isEqualToString:@"1"]) {
        wordOrderType = @"维护";
    } else if ([wordOrderType isEqualToString:@"2"]) {
        wordOrderType = @"拆机";
    } else if ([wordOrderType isEqualToString:@"3"]) {
        wordOrderType = @"移机";
    } else if ([wordOrderType isEqualToString:@"4"]) {
        wordOrderType = @"家访";
    }
    return wordOrderType;
}

@end
